//所有的数组添加计算总和的原型方法
Array.prototype.total = function () {
    return this.reduce((p, c) => {
            return p + c;
        }
    )
};


//文字分类:

// 图表分类:
// 饼图
function pie(config) {
    return {
        ...config, type: "pie",
        label: {
            normal: {
                textStyle: {
                    color: '#fff'
                }
            }
        },
    }
}
//二元环图
function ring(config) {
    return {
        radius: ["50%", "65%"],
        ...config,
        type: "pie",
        label: false,
        hoverAnimation: false
    }
}

//柱状图
function bar({name, data}) {
    return {
        name, data, type: "bar",
    }
}

//横向柱状图

function hbar({name, data}) {
    return {
        name, data, type: "bar",
    }
}

//圆点折线图
function dotLine({name, data}) {
    return {
        name, data, type: "line",
        symbolSize: 20,
    }
}

//普通折线图
function line({name, data, areaStyle}) {
    return {
        name, data,
        type: "line",
        areaStyle
    }
}


function ringText(data) {
    let rate = data[1] / data.total();
    let text = (rate * 100).toFixed(2);
    return `${text}%`;
}


function attachRing(option, jsConfig = {}) {
    let {position = {bottom: "0"},desc} = jsConfig;
    option.series[1] = ring({
        radius: ["0", "50%"],
        type: "pie",
        label: false,
        hoverAnimation: false,
        silent: true,
        data: [{
            name: "",
            value: 3,
            itemStyle: {
                color: "#fff"
            },
        }]
    });
    option.graphic = [
        {
            type: 'text',
            left: 'center',
            top: 'center',
            zlevel: 1,
            style: {
                text: ringText(option.series[0].data.map(each => {
                    return each.value;
                })),
                fill: "black",
            }

        },
        {
            type: 'text',
            left: 'center',
            ...position,
            zlevel: 1,
            style: {
                text: desc || "",
                fill: "white",
            }

        }
    ];
}


async function renderBy({reqConfig, jsConfig = {}}, ele) {
    const {paramsGetter = normalParamsGetter} = jsConfig;
    const {apiAddress, sumType, chartType, theme} = reqConfig;
    //从前端配置中,得到获取筛选参数的方法
    const params = paramsGetter();
    //筛选参数回传sumType
    params.sumType = sumType;
    const res = await axios.get(apiAddress, {params});
    const {data} = res;
    //获取到数据后,组装为echarts 的option;
    const {renderInfo} = jsConfig;
    renderInfo && renderInfo(data);
    let option;

    if (chartType === 'pie' || chartType === "ring") {
        //极坐标类型的解析
        option = assembleOptionPolar(data.data, jsConfig, reqConfig);
    } else {
        //直角坐标的解析
        option = assembleOption(data.data, jsConfig, reqConfig);
    }
    let chart = echarts.init(ele, theme || "shine");
    chart.setOption(option);
    window.addEventListener("resize", chart.resize);
}

function normalParamsGetter() {
    return {};
}

/*
* modelId,图表模块id,
* */
async function reqConfigure(modelId, jsConfig) {
    if (!modelId) {
        console.log("base.js:25->jsConfig", jsConfig);
        return;
    }
    let {data} = await axios.get("/common-model/getModelById", {params: {modelId}});
    return {
        //前端配置
        jsConfig,
        //请求的后端配置
        reqConfig: data.data
    }
}

//装配直角坐标系option
function assembleOption(data, jsConfig, reqConfig) {
    const {chartType, dimConfigList, preConfig} = reqConfig;//图表类型
    const {xAxisRotate = 0, yAxisRotate = 0} = jsConfig;
    // const legendData = [];
    const xAxisData = [];
    const series = [];
    data.map(item => {
        xAxisData.push(item[preConfig.columnCode]);
    });
    dimConfigList.map(dim => {
        //解析图例
        //从数据中解析横坐标及纵坐标
        let sData = [];
        data.map(item => {
            sData.push(item[dim.columnCode]);
        });
        //添加序列
        series.push(window[dim.chartType || chartType]({
            name: dim.columnName,
            data: sData
        }));
    });
    // series.map(each=>{
    //     legendData.push(each.name);
    // });

    let option = {
        tooltip: {
            trigger: 'item',
        },
        legend: {
            bottom: 0,
            textStyle: {
                color: '#fff'
            },
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
                rotate: xAxisRotate,
                color: "white"
            },
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                rotate: yAxisRotate,
            },
        },
        series
    };
    //类型为横向,则交换x,y数据
    if (chartType === 'hbar') {
        let temp = option.xAxis;
        option.xAxis = Object.assign(option.yAxis);
        option.yAxis = temp;
        // option.legend={};
    }
    console.log("base.js:108->option", option);
    return option;
}


//装配极坐标系option
function assembleOptionPolar(data, jsConfig, reqConfig) {
    const {chartType, dimConfigList, chartName} = reqConfig;//图表类型
    const datas = [];
    let total = 0;
    dimConfigList.map(dim => {
        //从数据中解析饼图数据
        datas.push({
            name: dim.columnName,
            value: data[dim.columnCode]
        });
        total += data[dim.columnCode];
    });
    let type = window[chartType];
    let option = {
        tooltip: {
            trigger: 'item',
            formatter: function ({name, value}) {
                const rate = (value / total * 100).toFixed(2);
                return `${name}:${value} <br/> 占比 ${rate}%`;
            }
        },
        legend: {
            name: "",
            bottom: 0,
            data: datas.map(each => {
                return each.name;
            }),
            textStyle: {
                color: '#fff'
            },
            show: type === pie
        },
        series: [
            type({
                name: "",
                data: datas,
            }),
        ]
    };

    if (chartType === 'ring') {
        attachRing(option, {
            ...jsConfig,
            desc: chartName
        });
    }
    console.log("base.js:160->option", option);
    return option;
}
